package com.example.pclimb.ui.guides;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.pclimb.R;
import com.example.pclimb.databinding.ActivityGuideDetailBinding;
import com.example.pclimb.model.TravelGuide;
import com.example.pclimb.model.User;
import com.example.pclimb.util.SharedPreferencesUtil;
import com.example.pclimb.viewmodel.TravelGuideViewModel;
import com.example.pclimb.viewmodel.UserLikeViewModel;
import com.example.pclimb.viewmodel.UserViewModel;

/**
 * 攻略详情页面
 */
public class GuideDetailActivity extends AppCompatActivity {

    private static final String TAG = "GuideDetailActivity";
    private ActivityGuideDetailBinding binding;
    private TravelGuideViewModel guideViewModel;
    private UserViewModel userViewModel;
    private UserLikeViewModel userLikeViewModel;
    private int guideId;
    private int currentUserId;
    private boolean viewCountIncreased = false; // 添加一个标志来追踪是否已经增加过浏览量
    private TravelGuide currentGuide; // 新增变量，用于存储当前攻略
    private boolean isLiked = false; // 是否已点赞

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityGuideDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 设置工具栏
        setSupportActionBar(binding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        binding.toolbar.setNavigationOnClickListener(v -> onBackPressed());

        // 获取当前用户ID
        currentUserId = SharedPreferencesUtil.getUserId(this);
        if (currentUserId <= 0) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化ViewModel
        guideViewModel = new ViewModelProvider(this).get(TravelGuideViewModel.class);
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        userLikeViewModel = new ViewModelProvider(this).get(UserLikeViewModel.class);

        // 从Intent获取攻略ID
        if (getIntent().hasExtra("guide_id")) {
            guideId = getIntent().getIntExtra("guide_id", -1);
            if (guideId == -1) {
                Toast.makeText(this, R.string.error_loading_data, Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
        } else {
            Toast.makeText(this, R.string.error_loading_data, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 设置点赞按钮视觉效果
        updateLikeButtonState();

        // 设置点赞按钮点击事件
        binding.btnLike.setOnClickListener(v -> {
            toggleLike();
        });

        // 加载攻略详情
        loadGuideDetails();
    }

    /**
     * 加载攻略详情
     */
    private void loadGuideDetails() {
        // 显示进度条
        binding.progressBar.setVisibility(View.VISIBLE);
        binding.scrollContent.setVisibility(View.GONE);

        // 获取攻略详情
        guideViewModel.getTravelGuideById(guideId).observe(this, guide -> {
            if (guide != null) {
                currentGuide = guide; // 存储当前攻略
                // 更新UI
                updateUI(guide);

                // 获取作者信息
                userViewModel.getUserById(guide.getAuthorId()).observe(this, author -> {
                    binding.progressBar.setVisibility(View.GONE);
                    binding.scrollContent.setVisibility(View.VISIBLE);

                    if (author != null) {
                        // 显示作者信息
                        binding.tvAuthor.setText(author.getNickname());
                    } else {
                        binding.tvAuthor.setText(R.string.unknown_author);
                    }
                });

                // 只在首次加载时增加浏览量
                if (!viewCountIncreased) {
                    increaseViewCount();
                    viewCountIncreased = true;
                }

                // 检查当前用户是否已点赞
                checkLikeStatus();
            } else {
                binding.progressBar.setVisibility(View.GONE);
                Toast.makeText(this, R.string.error_loading_data, Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    /**
     * 更新UI
     */
    private void updateUI(TravelGuide guide) {
        // 设置标题和详细信息
        binding.toolbar.setTitle(guide.getTitle());
        binding.tvTitle.setText(guide.getTitle());
        binding.tvLocation.setText(guide.getLocation());
        binding.tvContent.setText(guide.getContent());
        updateLikeCount(guide.getLikeCount());

        // 设置发布日期
        if (guide.getPublishDate() != null) {
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault());
            binding.tvPublishDate.setText(sdf.format(guide.getPublishDate()));
        } else {
            binding.tvPublishDate.setVisibility(View.GONE);
        }
    }

    /**
     * 检查点赞状态
     */
    private void checkLikeStatus() {
        if (currentUserId > 0 && guideId > 0) {
            userLikeViewModel.isLiked(currentUserId, guideId).observe(this, count -> {
                isLiked = count != null && count > 0;
                updateLikeButtonState();
            });

            // 从实际点赞表中获取点赞数
            userLikeViewModel.getLikeCount(guideId).observe(this, count -> {
                if (count != null) {
                    updateLikeCount(count);
                    
                    // 如果数据库中的点赞数与攻略中的点赞数不一致，更新攻略中的点赞数
                    if (currentGuide != null && currentGuide.getLikeCount() != count) {
                        currentGuide.setLikeCount(count);
                        guideViewModel.update(currentGuide);
                    }
                }
            });
        }
    }

    /**
     * 更新点赞按钮状态
     */
    private void updateLikeButtonState() {
        if (isLiked) {
            binding.btnLike.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_filled, 0, 0, 0);
            binding.btnLike.setText(R.string.liked);
        } else {
            binding.btnLike.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_outline, 0, 0, 0);
            binding.btnLike.setText(R.string.like);
        }
    }

    /**
     * 更新点赞数显示
     */
    private void updateLikeCount(int count) {
        binding.tvLikeCount.setText(String.valueOf(count));
    }

    /**
     * 增加浏览量
     */
    private void increaseViewCount() {
        if (currentGuide != null) {
            try {
                // 增加浏览量
                currentGuide.setViewCount(currentGuide.getViewCount() + 1);
                // 更新攻略
                guideViewModel.update(currentGuide);
            } catch (Exception e) {
                Log.e(TAG, "增加浏览量失败", e);
            }
        }
    }

    /**
     * 切换点赞状态
     */
    private void toggleLike() {
        if (currentUserId <= 0) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        if (currentGuide == null) {
            return;
        }

        try {
            userLikeViewModel.toggleLike(currentUserId, guideId, isLiked);
            
            // 更新UI反馈
            if (isLiked) {
                Toast.makeText(this, R.string.unlike_success, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, R.string.like_success, Toast.LENGTH_SHORT).show();
            }
            
            // 立即更新按钮状态以提供快速反馈
            isLiked = !isLiked;
            updateLikeButtonState();
            
            // 点赞数会通过LiveData自动更新，不需要在这里手动修改
        } catch (Exception e) {
            Log.e(TAG, "切换点赞状态失败", e);
            Toast.makeText(this, "操作失败，请稍后重试", Toast.LENGTH_SHORT).show();
        }
    }
}